﻿/* Write a program that downloads a file from Internet 
 * (e.g. http://www.devbg.org/img/Logo-BASD.jpg) and stores it the current directory. 
 * Find in Google how to download files in C#. 
 * Be sure to catch all exceptions and to free any used resources in the finally block.
*/

using System;
using System.Net;
using System.Web;
using System.IO;
using System.Security;

namespace _4.DownloadFile
{
    class Download
    {
        static void Main()
        {
            //initialize new webclient and Uri instances
            Console.Write("Enter url: ");
            Uri url = new Uri(@Console.ReadLine());
            WebClient myWebClient = new WebClient();
            
            //local filename
            string fileName = Path.GetFileName(url.LocalPath);
            try
            {
                myWebClient.DownloadFile(url, fileName);
            }
            catch (WebException webexc)
            {
                throw new WebException("The address provided is invalid, the filename is a null reference or no file was entered along with the BaseAddress url, or an error occurred while downloading the data. \r\nPlease check carefully whether you typed the url correctly " + webexc.Message);
            }
            catch (OverflowException oe)
            {
                throw new OverflowException("An overflow exception occurred. There is either no memory to buffer the file or the file is too big to fit on the hard disk, please see the debugger response below\r\n" + oe.Message);
            }
            catch (SecurityException se)
            {
                throw new SecurityException("The perform operation could not be performed for security reasons. Please check whether you have the requried privileges. " + se.Message);
            }
            finally {
                string localfile = Directory.GetCurrentDirectory() + fileName;
                Console.WriteLine("File downloaded to {0}", localfile);
                myWebClient.Dispose(); //dispose of any junk we won't use anymore
            }
        }
    }
}
